package ticket;

/**
 * @Author Stringzhua
 * @Date 2024/10/29 16:16
 * description:
 */
public class Test04 {
    public static void main(String[] args) throws InterruptedException {
        AddAndDecX addAndDec = new AddAndDecX();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                addAndDec.Add();
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                addAndDec.Dec();
            }
        };
        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(AddAndDec.count);
    }
}

class AddAndDecX {
    public static int count = 0;

    public void Add() {
        synchronized (AddAndDecX.class) {
            for (int i = 0; i < 10000; i++) {
                AddAndDec.count += 1;
            }
        }
    }

    //通过.class对象加锁
//    public void Dec() {
//        synchronized (AddAndDecX.class) {
//            for (int i = 0; i < 10000; i++) {
//                AddAndDec.count -= 1;
//            }
//        }
//    }

    //通过当前对象的字节码文件对象加锁
//    public void Dec() {
//        synchronized (this.getClass()) {
//            for (int i = 0; i < 10000; i++) {
//                AddAndDec.count -= 1;
//            }
//        }
//    }

    //静态方法上使用synchronized加锁,作用等同于 synchronized (AddAndDecX.class){}
    public static synchronized void Dec() {
        for (int i = 0; i < 10000; i++) {
            AddAndDec.count -= 1;
        }
    }
}
